using UnityEngine;
using UnityEngine.EventSystems;


[RequireComponent(typeof(CharacterController))]
public class MovementComponent : MonoBehaviour
{
    // 基础参数
    [SerializeField] private float baseSpeed = 5f;
    [SerializeField] private float rotationSpeed = 10f;
    private CharacterController _controller;

    // 速度修正系统
    private float _speedModifier = 1f;
    public float CurrentSpeed => baseSpeed * _speedModifier;


    /// <summary>
    /// 移动方向（暴露给其他组件）
    /// </summary>
    public Vector3 MoveDirection { get; private set; }


    public void Awake()
    {
        _controller = GetComponent<CharacterController>();
    }

    /// <summary>
    /// 沿主相机视角的六自由度移动
    /// </summary>
    public void MoveAndFaceMovementDirection(Vector3 inputAxis)
    {
        // 转换为世界空间方向
        Vector3 cameraForward = Camera.main.transform.forward;
        Vector3 cameraRight = Camera.main.transform.right;
        cameraForward.y = 0;
        cameraRight.y = 0;
        cameraForward.Normalize();
        cameraRight.Normalize();

        MoveDirection = (cameraForward * inputAxis.z + cameraRight * inputAxis.x).normalized;

        // 应用移动
        _controller.Move(CurrentSpeed * Time.deltaTime * MoveDirection);

        // 自动旋转
        if (MoveDirection != Vector3.zero)
        {
            Quaternion targetRot = Quaternion.LookRotation(MoveDirection);
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRot, rotationSpeed * Time.deltaTime);
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="worldDirection"></param>
    public void MoveInWorldSpaceAlongCamera(Vector3 worldDirection)
    {
        MoveDirection = Vector3.ProjectOnPlane(worldDirection, Vector3.up).normalized;
        _controller.Move(CurrentSpeed * Time.deltaTime * MoveDirection);
    }


    /// <summary>
    /// 速度|修正接口
    /// </summary>
    public void AddSpeedModifier(float modifier) => _speedModifier *= modifier;
    public void ResetSpeedModifier() => _speedModifier = 1f;
    public void RemoveSpeedModifier(float modifier) => _speedModifier /= modifier;
}